import magic
from fastapi import HTTPException
from config.settings import settings

class FileValidator:
    def __init__(self):
        self.mime = magic.Magic(mime=True)
    
    async def validate(self, file) -> bool:
        """验证视频文件"""
        try:
            # 检查文件大小
            file_size = 0
            chunk_size = 1024 * 1024  # 1MB chunks
            while chunk := await file.read(chunk_size):
                file_size += len(chunk)
                if file_size > settings.MAX_FILE_SIZE:
                    raise HTTPException(
                        status_code=400,
                        detail=f"文件过大，最大支持{settings.MAX_FILE_SIZE/1024/1024}MB"
                    )
            await file.seek(0)  # 重置文件指针
            
            # 检查文件类型
            file_type = self.mime.from_buffer(await file.read(2048))
            await file.seek(0)
            
            print(f"检测到的文件类型: {file_type}")  # 添加日志
            print(f"允许的文件类型: {settings.ALLOWED_MIME_TYPES}")  # 添加日志
            
            if file_type not in settings.ALLOWED_MIME_TYPES:
                raise HTTPException(
                    status_code=400,
                    detail=f"不支持的视频格式，支持的格式：{', '.join(settings.ALLOWED_EXTENSIONS)}"
                )
            
            return True
            
        except HTTPException:
            raise
        except Exception as e:
            raise HTTPException(
                status_code=400,
                detail=f"文件验证失败: {str(e)}"
            )

# 创建全局实例
file_validator = FileValidator() 